package com.sgb.kjwl.view.ui.activity.transport;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.util.Pair;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.sgb.capital.model.PayInfoEntity;
import com.sgb.capital.view.ui.activity.PersonPayActivity;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.api.UrlConfig;
import com.sgb.kjwl.databinding.ActivityPayQuotationForCompanyBinding;
import com.sgb.kjwl.model.entity.CarInfo;
import com.sgb.kjwl.model.entity.GoodsOrderEntity;
import com.sgb.kjwl.model.entity.OrderEntity;
import com.sgb.kjwl.model.entity.self.MyOfferDetailsEntity;
import com.sgb.kjwl.model.entity.transport.DiyFieldEntity;
import com.sgb.kjwl.utils.ActivityJump;
import com.sgb.kjwl.utils.DefaultUtil;
import com.sgb.kjwl.utils.NumberUtil;
import com.sgb.kjwl.view.constant.RouterKey;
import com.sgb.kjwl.view.event.LogisticsEvent;
import com.sgb.kjwl.view.event.WebEvent;
import com.sgb.kjwl.view.ui.activity.WebActivity;
import com.sgb.kjwl.view.ui.activity.transport.owner.TransportOrderDetailOwnerActivity;
import com.sgb.kjwl.view.ui.adapter.transport.DiyOrderAdapter;
import com.sgb.kjwl.viewmodel.transport.PayGoodsQuotationForCompanyViewModel;
import com.sgb.link.utils.RoundDialogHelper;
import com.swgk.core.dialog.RoundCornerDialog;
import com.swgk.core.event.EventConstant;
import com.swgk.core.event.MenuEvent;
import com.swgk.core.util.DateUtils;
import com.swgk.core.util.MToast;
import com.swgk.core.util.UiUtil;
import com.swgk.core.util.UserOperating;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: 黄淋
 * @date: 2022/1/10
 * @Description: 报价-确认接单  企业、团队
 */
public class PayQuotationOrderForCompanyActivity extends AppActivity {
    ActivityPayQuotationForCompanyBinding mBinding;
    PayGoodsQuotationForCompanyViewModel mViewModel;
    //车辆选择
    private final List<CarInfo> mCarList = new ArrayList<>();
    //自定义字段列表
    private List<DiyFieldEntity> mCustomList;
    private DiyOrderAdapter mCustomAdapter;
    GoodsOrderEntity mEntity = new GoodsOrderEntity();
    private static final int TO_GOODS_ORDER = 100;//跳转订单详情
    String orderNo;
    private String offerNo;
    MyOfferDetailsEntity myOfferDetailsEntity;
    private long payEndTime;
    private  String freightOrderNo;

    public static void start(Context context, OrderEntity entity) {
        Intent intent = new Intent(context, PayQuotationOrderForCompanyActivity.class);
        intent.putExtra(RouterKey.DATA, (Serializable) entity);
        context.startActivity(intent);
    }

    public static void start(Context context, String offerNo) {
        Intent intent = new Intent(context, PayQuotationOrderForCompanyActivity.class);
        intent.putExtra(RouterKey.STRING, offerNo);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    protected void initView() {
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_pay_quotation_for_company);
        mViewModel = new ViewModelProvider(this).get(PayGoodsQuotationForCompanyViewModel.class);
        mBinding.setLifecycleOwner(this);
        offerNo = getIntent().getStringExtra(RouterKey.STRING);
        mBinding.includeTitle.titleView.setText("确认接单");
        mBinding.includeTitle.ivBack.setOnClickListener(v -> {
            finish();
        });
        mBinding.tvCargoOrdersSubmit.setOnClickListener(this::onMultiClick);
        mBinding.tvCargoOrdersProtocol.setText(Html.fromHtml("确认提交即表示您已阅读并同意"
                + "<font color='#5792FD'>《经营帮货物运输协议》</font>全部内容"));
        initRecycler();
        initEvent();

        mViewModel.getOfferDetails(this, offerNo);
        mViewModel.detailsLiveData.observe(this, offerEntity -> {
            this.myOfferDetailsEntity = offerEntity;
            setShow(offerEntity);
        });
    }

    private void setShow(MyOfferDetailsEntity myOfferDetailsEntity) {
        freightOrderNo = myOfferDetailsEntity.getMessageOrderNo();
        if (!TextUtils.isEmpty(myOfferDetailsEntity.getOrderPayTime())) {
            payEndTime = System.currentTimeMillis() + Long.parseLong(myOfferDetailsEntity.getOrderPayTime());
        }
        String number = "1";
        if (myOfferDetailsEntity.getQuotationFreightUnit() == 1) {
            number = "1";
        } else if (myOfferDetailsEntity.getQuotationFreightUnit() == 2) {
            number = NumberUtil.trim0(myOfferDetailsEntity.getWeight());
        } else if (myOfferDetailsEntity.getQuotationFreightUnit() == 3) {
            number = NumberUtil.trim0(myOfferDetailsEntity.getVolume());
        }
        mBinding.gtdFreightUnitText.setText(String.format("单价%s%s x %s", NumberUtil.trim0(myOfferDetailsEntity.getFreight()), myOfferDetailsEntity.getQuoteFreightUnitWorls(), number));
        mBinding.gtdAllFreightPriceText.setText(String.format("%s元", NumberUtil.trim0(myOfferDetailsEntity.getAllFreight())));
        mBinding.gtdLocationText.setText(String.format("%s%s%s%s", DefaultUtil.getString(myOfferDetailsEntity.getProvinceName()), DefaultUtil.getString(myOfferDetailsEntity.getCityName()),
                DefaultUtil.getString(myOfferDetailsEntity.getDistrictName()), DefaultUtil.getString(myOfferDetailsEntity.getDetailAddress())));
        mBinding.gtdInTimeText.setText(DateUtils.stampToDay5(myOfferDetailsEntity.getInTime()));

        StringBuilder builder = new StringBuilder();
        if (myOfferDetailsEntity.getDriverAuths() != null && myOfferDetailsEntity.getDriverAuths().size() > 0) {
            for (int i = 0; i < myOfferDetailsEntity.getDriverAuths().size(); i++) {
                builder.append(myOfferDetailsEntity.getDriverAuths().get(i).getCarNumber()).append(" ");
            }
        }
        if (builder.length() > 1) {
            mBinding.gtdCarriageCarText.setText(builder.substring(0, builder.length() - 1));
        } else {
            mBinding.gtdCarriageCarText.setText("/");
        }
        mBinding.gtdBillInfoText.setText(myOfferDetailsEntity.getInvoiceInfo() != null ? myOfferDetailsEntity.getInvoiceInfo().getCompanyName() :
                myOfferDetailsEntity.getPersonalInvoiceInfo() != null ? myOfferDetailsEntity.getPersonalInvoiceInfo().getCompanyName() : "/");
        mBinding.gtdCarriagePromiseText.setText(TextUtils.isEmpty(myOfferDetailsEntity.getNote()) ? "/" : myOfferDetailsEntity.getNote());
        mBinding.gtdMarketingText.setText(TextUtils.isEmpty(myOfferDetailsEntity.getMarketingPublicity()) ? "/" : myOfferDetailsEntity.getMarketingPublicity());

        getCustomList(myOfferDetailsEntity);
        if (mCustomList != null && mCustomList.size() > 0) {
            mBinding.llAddTxt.setVisibility(View.VISIBLE);
            mCustomAdapter.setNewData(mCustomList);
        }
        if (myOfferDetailsEntity.getMessagePrice() != null && !NumberUtil.trim0(myOfferDetailsEntity.getMessagePrice()).equals("0")) {
            mBinding.tvCargoOrdersPrice.setText(NumberUtil.trim0(myOfferDetailsEntity.getMessagePrice()) + "元");
            mBinding.tvCargoOrdersSubmit.setText("提交订单并支付信息费");
        } else {
            mBinding.tvCargoOrdersPrice.setText("0元");
            mBinding.tvCargoOrdersSubmit.setText("提交订单");
        }
    }

    private void initRecycler() {
        mViewModel.getQuickBankList(this);

        //自定义字段列表
        mCustomList = new ArrayList<>();
        mCustomAdapter = new DiyOrderAdapter(mCustomList);
        mBinding.rvCargoOrdersField.setNestedScrollingEnabled(false);
        mBinding.rvCargoOrdersField.setLayoutManager(new LinearLayoutManager(this));
        mCustomAdapter.bindToRecyclerView(mBinding.rvCargoOrdersField);

    }

    private void initEvent() {
        mBinding.setOnClick(this);
        mViewModel.ldTradeNo.observe(this, tradeNo -> {
            UiUtil.sendMsg(EventConstant.EVENT_REFRESH_GOODS, tradeNo.getOrderNo());
            orderNo = tradeNo.getOrderNo();
            if (TextUtils.isEmpty(orderNo)) {
                MToast.showToast(this, "未获取到订单号");
                return;
            }

            if (UserOperating.getInstance().isCompany()) {
                if (myOfferDetailsEntity.getMessagePrice() != null && !NumberUtil.trim0(myOfferDetailsEntity.getMessagePrice()).equals("0")) {
                    RoundDialogHelper.showSingleDialog(getActivity(), "提示",
                            "已为您创建待付订单，请联系公司财务至 我的 - 资金中心 - 待付订单支付信息费。支付时效30分钟",
                            "确定", true, Color.parseColor("#5792FD"), new RoundDialogHelper.DialogFunction() {
                                @Override
                                public void normalRoundDialog() {
                                    EventBus.getDefault().post(LogisticsEvent.make().setMessageTag(EventConstant.EVENT_REFRESH_PAY_GOODS));
                                    ActivityJump.jumpToActivity(PayQuotationOrderForCompanyActivity.this, TransportOrderDetailOwnerActivity.class, Pair.create("no", orderNo),
                                            Pair.create("isGoodsOwner", TransportOrderDetailOwnerActivity.CAR_OWNER));
                                    finish();
                                }
                            });
                } else {
                    EventBus.getDefault().post(LogisticsEvent.make().setMessageTag(EventConstant.EVENT_REFRESH_PAY_GOODS));
                    ActivityJump.jumpToActivity(PayQuotationOrderForCompanyActivity.this, TransportOrderDetailOwnerActivity.class, Pair.create("no", orderNo),
                            Pair.create("isGoodsOwner", TransportOrderDetailOwnerActivity.CAR_OWNER));
                    finish();
                }
            } else if (UserOperating.getInstance().isTeam()) {
                if (BigDecimal.ZERO.compareTo(BigDecimal.valueOf(tradeNo.getAmount())) == 0) {
                    EventBus.getDefault().post(LogisticsEvent.make().setMessageTag(EventConstant.EVENT_REFRESH_PAY_GOODS));
                    ActivityJump.jumpToActivity(this, TransportOrderDetailOwnerActivity.class, Pair.create("no", orderNo),
                            Pair.create("isGoodsOwner", TransportOrderDetailOwnerActivity.CAR_OWNER));
                    finish();
                    return;
                }
                PayInfoEntity paymentEntity = new PayInfoEntity();
                paymentEntity.amount = tradeNo.getAmount();
                paymentEntity.orderId = tradeNo.getFreightOrderNo();
                PersonPayActivity.start(this, tradeNo.getFreightOrderNo());
                finish();
            }
        });
    }

    @Override
    public void onMultiClick(View v) {
        if (v == mBinding.includeTitle.ivBack) {
            finish();
        } else if (v == mBinding.tvCargoOrdersSubmit) {
            clearAllFocus();
            if (!mBinding.cbCargoOrdersProtocol.isChecked()) {
                MToast.showToast(this, "请先勾选运输协议");
                return;
            }
            if (UserOperating.getInstance().isTeam()) {
                if (!TextUtils.isEmpty(freightOrderNo) && payEndTime != 0 && System.currentTimeMillis() >= payEndTime) {
                    RoundDialogHelper.showSingleDialog(getActivity(), "提示", "超出支付有效时间，已为您取消",
                            "我知道了", true, R.color.color_5792FD, new RoundDialogHelper.DialogFunction() {
                                @Override
                                public void normalRoundDialog() {
                                    finish();
                                }
                            });
                    return;
                }
                if (!TextUtils.isEmpty(freightOrderNo) && myOfferDetailsEntity != null && !TextUtils.isEmpty(myOfferDetailsEntity.getMessagePrice())) {
                    PayInfoEntity paymentEntity = new PayInfoEntity();
                    paymentEntity.amount = Double.parseDouble(myOfferDetailsEntity.getMessagePrice());
                    paymentEntity.orderId = freightOrderNo;
                    PersonPayActivity.start(this, freightOrderNo);
                    finish();
                    return;
                }
            }
            toPayOrder();
        } else if (v == mBinding.tvCargoOrdersProtocol) {
            EventBus.getDefault().postSticky(WebEvent.make(EventConstant.EVENT_WEBVIEW, UrlConfig.NEW_BASE_URL + "logistics/operate/html/file/transportAgreement"));
            WebActivity.start(this);
        } else if (v == mBinding.ivRules) {
            showTextDialog(false);
        }
    }

    public void toPayOrder() {
        mEntity.setGoodsSourceNo(myOfferDetailsEntity.getSourceNo());
        mEntity.setCarOfferNo(myOfferDetailsEntity.getCarOfferNo());
        mEntity.setGoodsOfferNo(myOfferDetailsEntity.getGoodsOfferNo());
        mViewModel.quotation(this, mEntity);

    }

    public void showTextDialog(boolean isShowBotton) {
        View view = View.inflate(getActivity(), R.layout.dialog_order_rules, null);
        final RoundCornerDialog roundCornerDialog = new RoundCornerDialog(getActivity(), 0, 0, view, R.style.RoundCornerDialog);
        roundCornerDialog.show();
        roundCornerDialog.setCanceledOnTouchOutside(false);// 设置点击屏幕Dialog不消失
        TextView tv_sure = view.findViewById(R.id.tv_sure);
        ImageView img_cancel = view.findViewById(R.id.img_cancel);
        ConstraintLayout rl_content = view.findViewById(R.id.rl_content);
        if (isShowBotton) {
            tv_sure.setVisibility(View.VISIBLE);
            rl_content.setBackgroundResource(R.drawable.shape_circle_corner_white_half_5dp);
        }
        //确定
        tv_sure.setOnClickListener(v -> {
            if (isShowBotton) {
                toPayOrder();
            }
            roundCornerDialog.dismiss();
        });
        //取消
        img_cancel.setOnClickListener(v -> roundCornerDialog.dismiss());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) return;
        if (requestCode == TO_GOODS_ORDER) {//支付成功跳转订单详情
            UiUtil.sendMsg(EventConstant.EVENT_REFRESH_GOODS, null);
            EventBus.getDefault().post(LogisticsEvent.make().setMessageTag(EventConstant.EVENT_REFRESH_PAY_GOODS));
            ActivityJump.jumpToActivity(this, TransportOrderDetailOwnerActivity.class, Pair.create("no", orderNo),
                    Pair.create("isGoodsOwner", TransportOrderDetailOwnerActivity.CAR_OWNER));
            finish();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(MenuEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_ORDER_FINISH) {
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private List<DiyFieldEntity> getCustomList(MyOfferDetailsEntity mOrderEntity) {
        mCustomList.clear();
        if (mOrderEntity != null && mOrderEntity.getDiyField() != null && mOrderEntity.getDiyField().size() > 0) {
            for (int i = 0; i < mOrderEntity.getDiyField().size(); i++) {
                DiyFieldEntity singleItemEntity = new DiyFieldEntity();
                singleItemEntity.setKey(mOrderEntity.getDiyField().get(i).getKey());
                singleItemEntity.setValue(mOrderEntity.getDiyField().get(i).getValue());
                mCustomList.add(singleItemEntity);
            }
        }
        return mCustomList;
    }
}
